package com.gg.communication.model;

import java.util.concurrent.CompletableFuture;

/**
 * @author sakura
 * @since 2025-06-16
 */

public class MessageTask {
    private long sendTimeout = 3000;     // 发送等待超时5秒

    public long getSendTimeout() {
        return sendTimeout;
    }

    TaskState state;
    /**
     * 发送的消息
     */
    public final byte[] message;
    /**
     * 接收的消息
     */
    public byte[] revc;
    public final CompletableFuture<byte[]> future;
    public CompletableFuture<byte[]> receiveFuture;
    public long enqueueTime;
    private volatile boolean sent = false;
    private volatile boolean completed = false;

    /**
     * 已接受完成
     */
    private volatile boolean received = false;

    private int port;
    private String host;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public TaskState getState() {
        return state;
    }

    public void setState(TaskState state) {
        this.state = state;
    }

    public void setSendTimeout(long sendTimeout) {
        this.sendTimeout = sendTimeout;
    }

    public MessageTask(byte[] message, CompletableFuture<byte[]> future) {
        this.message = message;
        this.future = future;
        this.enqueueTime = System.currentTimeMillis();
        this.receiveFuture = new CompletableFuture<>();
        //this.sendTimeout = timeout;
    }


    public synchronized void receive() {
        this.received = true;
    }

    public boolean isReceived() {
        return received;
    }

    public synchronized void markAsSent() {
        this.sent = true;
    }

    public synchronized boolean isSent() {
        return sent;
    }

    public synchronized boolean isCompleted() {
        return completed || future.isDone();
    }

    public boolean isSendTimedOut() {
        boolean res = sent && (System.currentTimeMillis() - enqueueTime) > sendTimeout;
        return res;
    }
}
